<script setup>
    import { ref, provide, onMounted, watch, onUnmounted  } from 'vue'
    import {
        CirclePlus
    } from '@element-plus/icons-vue'
    import { useRouter, useRoute, onBeforeRouteUpdate } from 'vue-router';
    import { ElMessage, ElLoading } from "element-plus";
    import KnowledgePopup from '../../components/knowledgePopup/index.vue'
    import request from '../../request/axios'
    import { formatDateTimeWithTimestamp } from '../../utils/time'
    import { fileIco } from '../../utils'
    import FilePreview from '../../components/FilePreview/index.vue'
    import { downloadOnClick } from '../../utils/index'
    import { emitter } from '../../utils/eventBus.js'

    const router = useRouter();
    const route = useRoute()
    // const userInfo = ref({
    //     head: '',
    //     nickname: '',
    // })
    // const userMes = JSON.parse(localStorage.getItem('userInfo'))
    // userMes && (userInfo.value = userMes)

    const userMessage = ref(JSON.parse(localStorage.getItem('userInfo'))) // 用户信息
    const isMember = ref(0); // 是否会员
    const isCompanyMember = ref(0); // 是否企业会员
    const uploaded = ref(0); // 是否可以创建知识库
    
    onMounted(() => {
        isMember.value = 0
        uploaded.value = 0
        isCompanyMember.value = 0
        if (userMessage.value?.is_member) { isMember.value = userMessage.value?.is_member }
        if (userMessage.value?.uploaded) { uploaded.value = userMessage.value?.uploaded }
        if (userMessage.value?.is_company_member) { isCompanyMember.value = userMessage.value?.is_company_member }
        emitter.on('refresh-repository', handleRefresh)
    })
    onUnmounted(() => {
        emitter.off('refresh-repository', handleRefresh)
    })
    const handleRefresh = () => {
        searchContent.value = ''
        getKnowledgeList()
    }

    // 获取知识库列表
    const total = ref(0)
    const page = ref(1)
    const knowledgeList = ref([])
    const searchContent = ref('')
    const collectionLoading = ref(false)
    const getKnowledgeList = async () => {
        try {
            const loading = ElLoading.service({
                lock: true,
                text: '加载中...',
            })
            knowledgeList.value = []
            const apiUrl = `/v1/api-knowledge-list?page=${page.value}&pageNum=16&search=${searchContent.value}`
            const res = await request.getV2({ url: apiUrl })
            loading.close()
            if (res.data.length == 0) return
            knowledgeList.value = res.data?.list || []
            total.value = res.data.pageInfo.count
            collectionLoading.value = false;
        } catch (error) {
            console.log(error)
        }
    }
    getKnowledgeList()

    const changeKnowledge = (val) => {
        page.value = val;
        getKnowledgeList()
    }

    // 获取知识库列表
    provide('addKnowledge', data => {
        console.log(data);
        // try {
        //     const data = {}
        //     data.name = knowledgeName.value
        //     data.content = fileContent.value
        //     const res = await request.postV2({ url: '/v1/api-create-knowledgesave', data })
        //     if (res.code == 200) {
        //     }
        // } catch (error) {
        //     console.log(error)
        // }
        // collectionLoading.value = true;
        // getKnowledgeList()
    })
    
    provide('addKnowledgeMap', async (data) => {
        collectionLoading.value = true;
        try {
            const res = await request.postV2({ url: '/v1/api-create-knowledgesave', data })
            if (res.code != 200) return ElMessage.error(res.msg)
            getKnowledgeList()
        } catch (error) {
            console.log(error)
        }
    })

    // 新建知识库弹窗
    const kId = ref('')
    const popupType = ref('0')
    const knowledgeContent = ref('')
    const knowledgeContents = ref('')
    const knowledgePopupRef = ref(null);
    const clickAddRepository = (type) => {
        popupType.value = type;
        if (knowledgePopupRef.value) return knowledgePopupRef.value.setPopupBox();
    }

    // 删除知识库
    const clickDelKnowledge = async (row) => {
        if (row.type == 1 || row.type == 2) {
            try {
                const data = {}
                const apiUrl = row.type == 1 ? '/v1/api-folder-del' : '/v1/api-del-file'
                const loading = ElLoading.service({
                    lock: true,
                    text: '加载中...',
                })
                if (row.type == 1) {
                    data.folder_id = row.id
                } else {
                    data.knowledge_file_id = row.id
                }
                const res = await request.postV2({ url: apiUrl, data })
                loading.close()
                if (res.code == 200) {
                    getKnowledgeList();
                }
            } catch (error) {
                console.log(error)
            }
        } else {
            if (row.status == 1) return ElMessage.warning('知识库模型正在解析中~，无法删除')
            const loading = ElLoading.service({
                lock: true,
                text: '加载中...',
            })
            const data = {}
            data.knowledge_id = row.id
            const res = await request.postV2({ url: '/v1/api-folder-del', data })
            loading.close()
            if (res.code == 200) {
                getKnowledgeList()
                ElMessage.success("删除成功");
            }
        }
    }

    // 修改知识库
    const fileObj = ref({}) // 文件夹对象
    const clickUpKnowledge = (row) => {
        if (row.type == 3) {
             kId.value = row.id
            popupType.value = '1'
            knowledgeContent.value = row.knowledge_base_name
            knowledgeContents.value = row.knowledge_desc
            getKnowledgeList();
            if (knowledgePopupRef.value) return knowledgePopupRef.value.setPopupBox();
        } else if (row.type == 1) {
            popupType.value = '4'
            fileObj.value = row
            if (knowledgePopupRef.value) return knowledgePopupRef.value.setEditPopupBox(row);
        }
    }
    provide('fileMessage', data => {
        getKnowledgeList()
    })

    const selectedFile = ref(null);
    const drawerVisible = ref(false);
    const clickRepository = (item) => {
        if (item.type == 3) {
            localStorage.removeItem('breadcrumb')
            localStorage.setItem('breadcrumb', item.knowledge_base_name)
            const updated = item.updated
            const deleted = item.deleted
            router.push(`/fileList?knowledgeId=${item.id}&folderId=0&updated=${updated}&deleted=${deleted}`)
        } else if (item.type == 1) {
            return router.push(`/fileList?knowledgeId=${item.knowledge_id}&folderId=${item.id}`);
        } else if (item.type == 2) {
            selectedFile.value = item;
            drawerVisible.value = true;
        }
    }
    const downloadFile = () => {
        if (selectedFile.value && selectedFile.value.oss_url) {
            downloadOnClick(selectedFile.value.oss_url);
        }
    }
    const closeDrawer = () => {
        drawerVisible.value = false;
    }

    // 权限管理 S
    const classIdx = ref(0)
    const checkAll = ref(false)
    const isDelUser = ref(false)
    const dialogPermissionsVisible = ref(false)
    const addDialogPermissionsVisible = ref(false)
    const classListMap = ref(['添加人员', '添加组织机构', '添加群组',])
    const collaborationList = ref([{ name: 'demo1-cs' }, { name: 'demo2-cs' }, { name: 'demo3-cs' },])
    const permissionsUserList = ref([
        { name: 'demo1', id: 1, check: false },
        { name: 'demo2', id: 2, check: false },
        { name: 'demo3', id: 3, check: false },
    ])
    const prmissionsText = ref('')
    const prmissionsList = ref([])
    const clickPrmissions = (idx) => {
        prmissionsText.value = prmissionsList.value[idx].name
    }
    const clickDelUser = (idx) => {
        collaborationList.value.splice(idx, 1)
    }
    const clickCheckUser = (idx) => {
        permissionsUserList.value[idx].check = false
    }
    const changeCheckAll = (val) => {
        permissionsUserList.value.forEach(item => {
            item.check = val
        })
    }
    const getPermissions = async (e) => {
        const res = await request.getV2({ url: `/v1/api-permissions-list` })
        prmissionsList.value = res.data || []
        prmissionsText.value = prmissionsList.value[0].name
    }
    getPermissions()

    const knowledgeName = ref('')
    const clickPermissions = async (e) => {
        console.log(e);
        knowledgeName.value = e.knowledge_base_name
        const res = await request.getV2({ url: `v1/api-user-permissions?knowledge_id=${e.id}` })
        console.log(res.data);
        dialogPermissionsVisible.value = true
    }

    const defaultProps = {
        children: 'children',
        label: 'label',
        disabled: 'disabled',
    }

    const treeData = [
        {
            id: 1,
            label: '一级部门',
            children: [
                {
                    id: 3,
                    label: '二级部门 1-1',
                    children: [
                        {
                            id: 4,
                            label: '三级部门 1-1-1',
                        },
                        {
                            id: 5,
                            label: '三级部门 1-1-2',
                        },
                    ],
                },
                {
                    id: 2,
                    label: '二级部门 1-2',
                    children: [
                        {
                            id: 6,
                            label: '三级部门 1-2-1',
                        },
                        {
                            id: 7,
                            label: '三级部门 1-2-2',
                        },
                    ],
                },
            ],
        },
    ]

    const OneThreeArr = ref([1, 3])
    const formattingIcon = (name) => {
        if (!name) return
        return fileIco(name)
    }
    const fileIcon = (name) => {
        const icon = formattingIcon(name)
        const image = new URL(`../../assets/image/file-ico/ico-${icon}.png`, import.meta.url).href
        return image
    }
    const setTipsText = (item) => {
        if (item.type == 1) return item.content || '暂无描述';
        return item.status == 1 ? '正在解析中~' : '已解析';
    }
    // 权限管理 E
</script>

<template>
    <div class="content-repository">
        <div class="collection-title">
            <span>我的知识库</span>
            <div class="head-right">
                <div class="input-box">
                    <el-input v-model="searchContent" class="input" type="text" placeholder="搜索知识库" />
                    <el-button @click="getKnowledgeList()" class="sel-icon">
                        <img src="../../assets/image/icon/query.png" />
                    </el-button>
                </div>
                <div style="position: relative;margin-left: 10px;" v-if="uploaded != 0 || isMember != 0 || isCompanyMember != 0">
                    <el-button class="add-repository" :icon="CirclePlus"
                        @click="clickAddRepository('0')">新建知识库</el-button>
                </div>
            </div>
        </div>
        <div class="collection-list overflow-none">
            <div v-for="(item, index) in knowledgeList" :key="index" class="collection-item" @click="clickRepository(item)">
                <div v-if="item.selected == 1">
                    <div class="item-title">
                        <img v-if="item.type == 1" class="w-28-r4" src="../../assets/image/icon/collection-file.png" />
                        <img v-else-if="item.type == 2" :src="fileIcon(item.name)" class="w-28-r4" style="width: 20px;">
                        <img v-else class="w-28-r4" src="../../assets/image/icon/collection-icon.png" />
                        <div style="text-align:left;flex:1;" class="nowrap-hide">
                            {{item.knowledge_base_name || item.name}}
                        </div>
                        <!-- 权限管理 -->
                        <!-- <el-tooltip effect="dark" content="权限管理" placement="top">
                        <Operation @click.stop="clickPermissions(item)"
                            style="width: 20px;color: #999;margin-right: 8px;" />
                    </el-tooltip> -->
                        <img class="w-20" v-if="OneThreeArr.includes(item.type) && item.updated == 1" 
                            @click.stop="clickUpKnowledge(item)"
                            style="margin-right: 4px;" src="../../assets/image/icon/collection-updata.png" />
                        <el-popover placement="top" :width="160">
                            <template #reference>
                                <img class=" w-20" v-if="item.deleted == 1"
                                    src="../../assets/image/icon/collection-del.png" />
                            </template>
                            <div class="popover-content">
                                <span>确定删除该知识库？</span>
                                <el-button @click="clickDelKnowledge(item)" size="small" class="popover-btn"
                                    type="primary">确定</el-button>
                            </div>
                        </el-popover>
                    </div>
                    <div class="qufen">
                        <div v-if="item.type == 1 || item.type == 2" class="item-tips nowrap-hide-2">
                            {{setTipsText(item)}}
                        </div>
                        <div v-else class="item-tips nowrap-hide-2">{{item.knowledge_desc || '该知识库暂无描述~'}}</div>
                    </div>
                    <div class="item-bottom">
                        <div style="display: flex;align-items: center;">
                            <!-- <img class="w-20" v-if="userInfo.head" :src="userInfo.head" />
                        {{userInfo.nickname}} -->
                        </div>
                        <span class="item-time">{{formatDateTimeWithTimestamp(item.create_time)}}</span>
                    </div>
                </div>
            </div>
            <!-- 上传状态 -->
            <div class="collection-item" v-if="collectionLoading" element-loading-text="上传中..."
                v-loading="collectionLoading"></div>
            <!-- 分页 -->
            <div class="pagination-content" v-if="total > 16">
                <el-pagination background layout="prev, pager, next" @current-change="changeKnowledge" :total="total"
                    :page-size="16" />
            </div>
        </div>
        <el-empty :image-size=" 200" description="暂无数据" v-if="knowledgeList.length === 0" />
        <KnowledgePopup :popupType="popupType" :knowledgeContent="knowledgeContent" :kId="kId"
            :knowledgeContents="knowledgeContents" :fileObj="fileObj" ref="knowledgePopupRef" />

        <!-- 权限管理弹窗 -->
        <el-dialog v-model="dialogPermissionsVisible" title="权限管理" width="600">
            <div class="permissions">
                <div class="repository-name">
                    <img class="w-28-r4" src="../../assets/image/icon/collection-icon.png" />{{knowledgeName || '--'}}
                </div>
                <div class="collaboration-box">
                    <div class="collaboration-title">
                        <span>协作者</span>
                        <div>
                            <el-button size="small" @click="isDelUser = !isDelUser">{{isDelUser?'完成':'管理'}}</el-button>
                            <el-button size="small" @click="addDialogPermissionsVisible = true">添加</el-button>
                        </div>
                    </div>
                    <div class="collaboration-user">
                        <div class="user-item" v-for="(item, index) in collaborationList" :key="index">
                            <img class="w-20" src="../../assets/image/icon/user.png" />
                            <span>{{item.name}}</span>
                            <Close class="user-close" @click="clickDelUser(index)" v-if="isDelUser" />
                        </div>
                    </div>
                </div>

            </div>
        </el-dialog>

        <!-- 添加权限管理弹窗 -->
        <el-dialog v-model="addDialogPermissionsVisible" title="添加协作者" width="600">
            <div class="permissions">
                <div class="class-box">
                    <div class="class-list">
                        <div :class="['class-name',{'action': classIdx === index}]" v-for="(item,index) in classListMap"
                            @click="classIdx = index" :key="index">{{item}}
                        </div>
                    </div>
                    <el-checkbox v-model="checkAll" v-if="classIdx != 1" @change="changeCheckAll">全选</el-checkbox>
                </div>

                <div class="permissions-tree" v-if="classIdx == 1">
                    <el-tree :data="treeData" :props="defaultProps" show-checkbox />
                </div>

                <div class="permissions-box" v-if="classIdx != 1">
                    <div class="permissions-left">
                        <div class="permissions-item" v-for="(item,index) in permissionsUserList" :key="index">
                            <el-checkbox v-model="item.check" style="margin-right: 6px;" />
                            <img v-if="classIdx == 0" class="w-20" src="../../assets/image/icon/user.png" />
                            <span>{{item.name}}</span>
                        </div>
                    </div>
                    <div class="permissions-right">
                        <div v-for="(item,index) in permissionsUserList" :key="index">
                            <div class="permissions-item" v-if="item.check">
                                <img v-if="classIdx == 0" class="w-20" src="../../assets/image/icon/user.png" />
                                <span>{{item.name}}</span>
                                <Close class="user-close" @click="clickCheckUser(index)" />
                            </div>
                        </div>
                    </div>
                </div>

                <div class="permissions-btn">
                    <el-dropdown placement="top">
                        <el-button type="info">
                            {{prmissionsText}}
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item v-for="(item,index) in prmissionsList" @click="clickPrmissions(index)"
                                    :key="index">{{item.name}}</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                    <el-button type="primary" style="margin-left: 12px;"
                        @click="addDialogPermissionsVisible = false">添加</el-button>
                </div>

            </div>
        </el-dialog>

        <!-- 文件预览抽屉 -->
        <el-drawer v-model="drawerVisible" :title="selectedFile?.name || '文件预览'" direction="rtl" size="50%"
            :destroy-on-close="false" :before-close="closeDrawer" custom-class="file-preview-drawer">
            <template #header>
                <div class="drawer-header">
                    <span>{{ selectedFile?.name || '文件预览' }}</span>
                    <div class="drawer-actions">
                        <el-button type="primary" size="small" @click="downloadFile">
                            <el-icon>
                                <download />
                            </el-icon>下载
                        </el-button>
                    </div>
                </div>
            </template>
            <FilePreview :file="selectedFile" :visible="drawerVisible" />
        </el-drawer>
    </div>
</template>

<style scoped lang="scss">
    .permissions {

        .repository-name {
            font-size: 16px;
            font-weight: bold;
            color: #333;
            display: flex;
            align-items: center;
        }

        .collaboration-box {
            .collaboration-title {
                font-size: 16px;
                color: #333;
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-top: 12px;
            }

            .collaboration-user {
                display: flex;
                align-items: center;
                flex-wrap: wrap;

                .user-item {
                    display: flex;
                    align-items: center;
                    margin-top: 12px;
                    margin-right: 12px;
                    padding: 4px 10px;
                    border-radius: 4px;
                    background-color: #f0f0f0;

                    img {
                        border-radius: 50%;
                    }

                    span {
                        padding: 4px;
                    }

                    .user-close {
                        width: 18px;

                        &:hover {
                            color: red;
                            cursor: pointer;
                        }
                    }
                }
            }
        }

        .class-box {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .class-list {
                display: flex;
                align-items: center;

                .class-name {
                    border: 1px solid #999;
                    padding: 4px 10px;
                    font-size: 15px;
                    color: #555;
                    margin-right: 10px;
                    border-radius: 4px;
                    box-shadow: 0px 0px 7px 0px rgba(0, 0, 0, 0.08);
                    cursor: pointer;

                    &.action {
                        color: #2D66B3;
                        border: 1px solid #2D66B3;
                    }
                }
            }
        }

        .permissions-tree {
            border: 1px solid #eee;
            border-radius: 8px;
            margin-top: 12px;
            height: 280px;
            overflow: auto;
            padding: 20px 0;
            width: 100%;
        }

        .permissions-box {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .permissions-left,
            .permissions-right {
                width: 49%;
                border: 1px solid #eee;
                border-radius: 8px;
                margin-top: 12px;
                height: 280px;
                overflow: auto;
                padding: 20px 0;
            }

            .permissions-item {
                display: flex;
                align-items: center;
                justify-content: space-between;
                height: 20px;
                border: 1px solid #eee;
                padding: 10px 6px;
                border-radius: 8px;
                margin: 0 10px 8px;

                .user-close {
                    width: 18px;
                }

                span {
                    margin: 0 8px;
                    display: block;
                    flex: 1;
                }
            }
        }

        .permissions-btn {
            margin-top: 20px;
            display: flex;
            justify-content: flex-end
        }
    }

    .popover-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;


        span {
            font-size: 14px;
            color: #666666;
        }

        .popover-btn {
            width: 80%;
            margin-top: 6px;
        }
    }

    .pagination-content {
        display: flex;
        width: 100%;
        align-items: center;
        justify-content: end;
        margin-top: 10px;
    }

    .w-28-r4 {
        width: 28px;
        margin-right: 4px;
    }

    .w-20 {
        width: 20px;
    }

    .content-repository {
        overflow: hidden;
        overflow-y: auto;
        padding: 50px 0;
        width: 1000px;

        :deep(.el-popover.el-popper) {
            padding: 0 !important;
        }

        .collection-title {
            font-size: 20px;
            font-weight: bold;
            color: #000000;
            margin-bottom: 18px;
            padding: 0;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .head-right {
                display: flex;
                align-items: center;

                .input-box {
                    width: 400px;
                    height: 40px;
                    overflow: hidden;
                    border-radius: 73px;
                    background: #FFFFFF;
                    position: relative;

                    &::after {
                        content: '';
                        width: 20px;
                        height: 40px;
                        background: #fff;
                        position: absolute;
                        right: 20px;
                        top: 0px;
                    }

                    .input {
                        width: 370px;
                        height: 44px;
                        margin-left: -2px;
                        margin-top: -2px;
                    }

                    .sel-icon {
                        width: 50px;
                        height: 34px;
                        background: #2D66B3;
                        position: absolute;
                        z-index: 999;
                        right: 5px;
                        top: 3px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        border-radius: 73px;

                        img {
                            width: 20px;
                            height: 20px;
                        }
                    }
                }

                .add-repository {
                    width: 160px;
                    height: 40px;
                    color: #fff;
                    font-size: 16px;
                    border-radius: 8px;
                    background: #2D66B3;

                }
            }
        }

        .collection-list {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            justify-content: flex-start;

            .collection-item {
                width: calc(100% / 3 - 26px);
                height: 120px;
                overflow: hidden;
                /* width: 363px; */
                margin: 0 7px 14px;
                border-radius: 8px;
                background: #FFFFFF;
                padding: 6px;
                cursor: pointer;
                box-shadow: 0px 0px 7px 0px rgba(0, 0, 0, 0.08);

                .item-title {
                    padding: 0 10px 0 6px;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                }

                .item-tips {
                    font-size: 14px;
                    color: #666;
                    line-height: 24px;
                    margin: 10px;
                    min-height: 50px;
                }

                .item-bottom {
                    display: flex;
                    align-content: inherit;
                    justify-content: space-between;
                    font-size: 13px;
                    padding: 0 10px;
                    color: rgba(153, 153, 153, 0.7);

                    img {
                        width: 20px;
                        height: 20px;
                        margin-right: 10px;
                        border-radius: 50%;
                        background-color: #eee;
                    }
                }
            }
        }
    }
</style>